<template>
  <a-card class="columns">
    <s-tool-bar>
      <template #left>
        <s-button type="primary" icon="plus-outlined" @click="addRow">添加</s-button>
        <s-button type="primary" icon="plus-outlined" @click="$refs.batchAdd.open()">批量添加</s-button>
        <s-button type="primary" icon="arrow-up-outlined" @click="autoImport">自动导入</s-button>
      </template>
      <template #right>
        <a-tooltip>
          <template #title> 勾选此选项后，可对列进行拖拽排序 </template>
          <a-checkbox :default-checked="true" @change="(e) => {
              draggable = e.target.checked ? true : false
            }
            ">拖拽排序</a-checkbox>
        </a-tooltip>
        <s-button type="default" icon="left-outlined" @click="$parent.openList()">返回</s-button>
        <s-button type="primary" icon="save-outlined" @click="save">保存</s-button>
      </template>
    </s-tool-bar>
    <s-scroll style="height: calc(100vh - 250px)">
      <a-form ref="form" :model="formValue">
        <s-table ref="table" :value="formValue.tableData" bordered :check-enable="false" :scroll="{ y: 450 }"
          :pageable="false" :columns="columns" :custom-row="draggable ? customRow : null">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'action'">
              <a-popconfirm title="确认删除此条数据？" ok-text="是" cancel-text="否" @confirm="deleteByIndex(index)">
                <a style="margin-right: 8px"> <s-icon type="delete-outlined" />删除 </a>
              </a-popconfirm>
            </template>
            <template v-else-if="column.key == 'dbName'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :rules="[{ required: true, message: '不能为空' }]"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }">
                <s-input v-model="record[column.key]" placeholder="数据库字段名称"> </s-input>
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'name'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :rules="[{ required: true, message: '不能为空' }]"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }">
                <s-input v-model="record[column.key]" placeholder="名称"> </s-input>
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'dbType'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :rules="[{ required: true, message: '不能为空' }]"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }">
                <s-select v-model="record[column.key]" :data="dicts.DATABASE_FIELD_TYPE" placeholder="数据库字段类型">
                </s-select>
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'dbLength'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }"
                :rules="[{ required: true, message: '不能为空' }]">
                <s-input-number v-model="record[column.key]" :min="0" :max="5000" placeholder="数据库字段长度" />
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'dbLength2'">
              <a-form-item v-if="record.dbType == 'double'" :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }"
                :rules="[{ required: true, message: '不能为空' }]">
                <s-input-number v-model="record[column.key]" :min="0" :max="100" placeholder="数据库字段精度" />
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'javaType'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }"
                :rules="[{ required: true, message: '不能为空' }]">
                <s-select v-model="record[column.key]" placeholder="数据类型" :data="dicts.JAVA_TYPE" />
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'key'">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }"
                :rules="[{ required: true, message: '不能为空' }]">
                <s-input v-model="record[column.key]" placeholder="数据编码,驼峰格式"> </s-input>
              </a-form-item>
            </template>

            <template v-else-if="column.key == 'add' ||
              column.key == 'update' ||
              column.key == 'query' ||
              column.key == 'listReturn' ||
              column.key == 'detailReturn' ||
              column.key == 'allowNull' ||
              column.key == 'sort'
              ">
              <a-form-item :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }">
                <s-switch v-model="record[column.key]" check-value="1" un-check-value="0">
                </s-switch>
              </a-form-item>
            </template>
            <template v-else-if="column.key == 'queryType'">
              <a-form-item v-if="record.query == '1'" :name="['tableData', index, column.key]" :colon="false"
                :options="{ labelWidth: 0, wrapperWidth: 24, offsetWidth: 0, total: 24 }">
                <s-select v-model="record[column.key]" placeholder="查询方式" :data="dicts.MATCH_TYPE">
                </s-select>
              </a-form-item>
            </template>
          </template>
        </s-table>
      </a-form>
    </s-scroll>
    <batch-add ref="batchAdd" @success="onBatchAdd"></batch-add>
  </a-card>
</template>

<script>
import { v4 } from 'uuid'
import BatchAdd from './BatchAdd.vue'
export default {
  name: 'Column',
  components: { BatchAdd },
  props: {
    dataId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      draggable: true,
      dicts: {
        DATABASE_FIELD_TYPE: [],
        JAVA_TYPE: [],
        MATCH_TYPE: []
      },
      columns: [
        {
          title: '名称',
          key: 'name',
          width: 150,
          fixed: 'left'
        },
        {
          title: '数据编码',
          key: 'key',
          width: 150
        },
        {
          title: '数据类型',
          key: 'javaType',
          width: 150
        },
        {
          title: '字段名称',
          key: 'dbName',
          width: 150
        },
        {
          title: '字段类型',
          key: 'dbType',
          width: 150
        },
        {
          title: '字段长度',
          key: 'dbLength',
          width: 150
        },
        {
          title: '字段精度',
          key: 'dbLength2',
          width: 150
        },
        {
          title: '可空',
          key: 'allowNull',
          width: 65
        },
        {
          title: '排序',
          key: 'sort',
          width: 65
        },
        {
          title: '添加',
          key: 'add',
          width: 65
        },
        {
          title: '编辑',
          key: 'update',
          width: 65
        },

        {
          title: '查询',
          key: 'query',
          width: 65
        },
        {
          title: '查询方式',
          key: 'queryType',
          width: 100
        },
        {
          title: '列表返回',
          key: 'listReturn',
          width: 100
        },
        {
          title: '详情返回',
          key: 'detailReturn',
          width: 100
        },
        {
          title: '操作',
          fixed: 'right',
          key: 'action',
          width: 100
        }
      ],
      formValue: {
        tableData: []
      }
    }
  },
  created() {
    this.$api
      .GET('/data/dict/item/selectListByGroupId', {
        groupIds: 'DATABASE_FIELD_TYPE,JAVA_TYPE,MATCH_TYPE'
      })
      .then((res) => {
        if (res.data) {
          Object.keys(res.data).forEach((key) => {
            const groups = []
            res.data[key].forEach((item) => {
              groups.push({ label: item.text, value: item.value })
            })
            this.dicts[key] = groups
          })
        }
      })
    this.$loading(true)
    this.$api
      .GET('/code/model/selectOneById', { id: this.dataId })
      .then((res) => {
        this.$loading(false)
        const modelColumn = res.data.modelColumn
        const tableData = []
        if (modelColumn && modelColumn.length > 0) {
          modelColumn.forEach((item) => {
            tableData.push({
              ...item,
              id: v4()
            })
          })
        }
        this.formValue.tableData = tableData
      })
      .catch((e) => {
        this.$loading(false)
      })
  },
  methods: {
    onColumnOrderChange() {
      if (this.startDataIndex != null && this.endDataIndex != null) {
        let item = this.formValue.tableData.splice(this.startDataIndex, 1)
        this.formValue.tableData.splice(this.endDataIndex, 0, item[0])
      }
    },
    deleteByIndex(index) {
      this.formValue.tableData.splice(index, 1)
    },
    onBatchAdd(row) {
      for (let i = 0; i < row.fieldNum; i++) {
        let item = JSON.parse(JSON.stringify(row))
        item.id = v4()
        item.name = item.name + (i + item.startIndex)
        item.key = item.key + (i + item.startIndex)
        item.dbName = item.dbName + (i + item.startIndex)
        this.formValue.tableData.push(item)
      }
    },
    addRow() {
      this.formValue.tableData.push({
        id: v4(),
        javaType: 'String',
        dbType: 'varchar',
        add: '1',
        update: '1',
        query: '1',
        queryType: '1',
        listReturn: '1',
        detailReturn: '1',
        sort: '1',
        allowNull: '1',
        dbLength: 255
      })
    },
    save() {
      const form = this.$refs.form
      form.validate().then((values) => {
        let keys = {}
        let keys2 = {}
        values.tableData.forEach((val) => {
          let key = val.key
          let count = keys[key]
          if (count) {
            count = count + 1
          } else {
            count = 1
          }
          keys[key] = count
          key = val.dbName
          count = keys2[key]
          if (count) {
            count = count + 1
          } else {
            count = 1
          }
          keys2[key] = count
        })
        let dumpKey
        Object.keys(keys).forEach((key) => {
          if (keys[key] > 1) {
            dumpKey = key
          }
        })
        Object.keys(keys2).forEach((key) => {
          if (keys2[key] > 1) {
            dumpKey = key
          }
        })
        if (dumpKey) {
          this.$message.warn(dumpKey + '重复')
        } else {
          const data = {
            id: this.dataId,
            modelColumn: values.tableData
          }
          this.$loading(true)
          this.$api
            .PUT('/code/model/updateModelColumn', data)
            .then((res) => {
              this.$loading(false)
              this.$message.info(res.msg)
            })
            .catch(() => {
              this.$loading(false)
            })
        }
      })
    },
    autoImport() {
      this.$loading(true)
      this.$api
        .GET('/code/model/findTableMetaData', { id: this.dataId })
        .then((res2) => {
          this.$loading(false)
          this.formValue.tableData = []
          for (let i = 0; i < res2.data.columns.length; i++) {
            let tmp = res2.data.columns[i]
            if (
              tmp.name == 'CREATE_BY' ||
              tmp.name == 'CREATE_DATE' ||
              tmp.name == 'CREATE_BY_ACCOUNT' ||
              tmp.name == 'UPDATE_BY' ||
              tmp.name == 'UPDATE_DATE' ||
              tmp.name == 'UPDATE_BY_ACCOUNT' ||
              tmp.name.indexOf('REMARK') == 0
            ) {
              continue
            }
            if (!tmp.primary) {
              let item = {
                key: tmp.moduleName,
                dbName: tmp.name,
                name: tmp.remark,
                id: v4(),
                javaType: 'String',
                dbType: 'varchar',
                add: '1',
                update: '1',
                query: '1',
                queryType: '1',
                listReturn: '1',
                detailReturn: '1',
                sort: '1',
                dbLength: tmp['length'],
                allowNull: tmp.nullAble ? '1' : '0'
              }
              this.formValue.tableData.push(item)
            }
          }
        })
        .catch((e2) => {
          this.$loading(false)
        })
    },
    customRow(column, index) {
      return {
        style: {
          cursor: 'pointer'
        },
        onMouseleave: (event) => { },
        onMouseenter: (event) => {
          // 兼容IE
          var ev = event || window.event
          ev.target.draggable = true
        },
        // 开始拖拽
        onDragstart: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          this.startDataIndex = index
        },
        // 拖动元素经过的元素
        onDragover: (event) => {
          this.endDataIndex = index
          // 兼容 IE
          var ev = event || window.event
          // 阻止默认行为
          ev.preventDefault()
        },
        // 鼠标松开
        onDrop: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          ev.target.draggable = false
          this.onColumnOrderChange()
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.columns:deep(td.ant-table-cell) {
  padding: 5px;
}
</style>
